package com.aurora.app.interceptor;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import com.aurora.app.constant.Conf;
import com.aurora.app.dao.UserDao;
import com.aurora.app.entity.User;
import com.aurora.app.entity.WeixinAppToken;
import com.aurora.app.service.WeixinAppTokenService;
import com.aurora.app.service.WeixinService;

/**
 * Socket建立连接（握手）和断开
 * 
 */
public class HandShakeInterceptor implements HandshakeInterceptor {
	private final Logger LOG = LoggerFactory.getLogger(this.getClass());
	//获取用户code
	private final static String user_code_url= "https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect";
		
	@Resource
	private WeixinAppTokenService weixinAppTokenService;
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
    	
    	if (request instanceof ServletServerHttpRequest) {
			ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
			HttpSession session = servletRequest.getServletRequest().getSession(false);
			// 标记用户
			String uid = ((User)session.getAttribute("user")).getId();
			
			if(StringUtils.isNotBlank(uid)){
				attributes.put("uid", uid);
			}else{
				WeixinAppToken weixinAppToken = this.weixinAppTokenService.findById(Conf.USED2_ID);
				if(weixinAppToken == null){
					return false;
				}else{
					//获取code
					String requestUrl =  user_code_url.replaceAll("APPID",weixinAppToken.getAppId()).
							replaceAll("REDIRECT_URI","http://www.used2.cn/used2/api/weixin/login.do").replaceAll("SCOPE","snsapi_userinfo");
					LOG.info(requestUrl);
					ServletServerHttpResponse servletResponse =(ServletServerHttpResponse)response;
					servletResponse.getServletResponse().sendRedirect(requestUrl);
					return false;
				}
			}
    	}
    	return true;
    }
 
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {
    
    }
	
 
}
